package control;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.State;
import interfaces.IState;

public class CState implements IState {
  private CConnection db;
  
  public CState(CConnection db) {
	this.db = db;
  }

  @Override
  public boolean create(State state) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
	int i = s.executeUpdate("INSERT INTO State VALUES (" + state.getId() + ", '" + state.getName() + "')");
	return i > 0;
  }

  @Override
  public boolean update(State state) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("UPDATE State SET State_Name = '" + state.getName() + "' WHERE stateID = " + state.getId());
	return i > 0;
  }

  @Override
  public boolean delete(State state) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("DELETE FROM State WHERE stateID = " + state.getId());
	return i > 0;
  }

  @Override
  public ArrayList<State> retrieveByID(int id) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from state where stateID = " + id);
    ArrayList<State> states = new ArrayList<State>();
    
    while(res.next()) {
      State f = new State();
      f.setId(res.getInt("stateID"));
      f.setName(res.getString("State_Name"));
      states.add(f);
    }
    
    return states;
  }

  @Override
  public ArrayList<State> retrieveAll() throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from state");

    ArrayList<State> states = new ArrayList<State>();
	    
    while(res.next()) {
      State f = new State();
      f.setId(res.getInt("stateID"));
      f.setName(res.getString("State_Name"));
      states.add(f);
    }

    return states;
  }
}
